<?php

namespace app\admin\controller\deerhome;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 页面设计
 *
 * @icon fa fa-circle-o
 */
class Design extends Backend
{

    /**
     * Evaluate模型对象
     * @var \app\admin\model\deerhome\Design
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\deerhome\Design;

    }
    public function index()
    {
        if (!$this->request->isAjax())
        {
            $page=$this->request->param('page','home','trim');
            $pageList=$this->model->order('weigh ASC')->select();
            $pageData=[];
            $hasMallPage=false;
            foreach ($pageList as $key => $value) {
                if($value['page']=='mall'){
                    $hasMallPage=true;
                }
                if($value['page']==$page){
                    $pageData=\json_decode($value['con'],true);
                    if(!$pageData){
                        $pageData=[];
                    }
                }
            }
            //初始化商城页面
            if(!$hasMallPage){
                $mallData=[
                    'page'=>'mall',
                    'page_title'=>'百货商城',
                    'con'=>\json_encode([
                        'banner'=>[]
                    ],JSON_UNESCAPED_UNICODE),
                    'weigh'=>2,
                    'update_time'=>date("Y-m-d H:i:s")
                ];
                $this->model->create($mallData);
                $pageList=$this->model->order('weigh ASC')->select();
            }
            if(count($pageData)==0 && $page!="cate"){
                $this->error("设计页面异常，请联系客服");
            }
            $this->assign("pageList", $pageList);
            $this->assign("pageData", $pageData);
            if($page=="home"){
                $this->assign("dataHome", $this->data_home());
            }
            return $this->view->fetch();
        }
        $page_id=$this->request->param('page-id','','trim');
        $page_block=$this->request->param('page-block','','trim');
        $params = $this->request->post('row/a',[]);
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if(!isset($params[$page_block])){
            $params[$page_block]=[];
        }
        if($page_block=="tags"){
            $params[$page_block]=explode(",",$params[$page_block]);
        }
        
        $data=$this->model->where("page",$page_id)->find();
        if(!$data){
            $this->error("页面不存在");
        }
        $con=\json_decode($data['con'],true);
        $con[$page_block]=$params[$page_block];
        $this->model->where("page",$page_id)->update([
            'con'=>\json_encode($con,JSON_UNESCAPED_UNICODE),
            'update_time'=>date("Y-m-d H:i:s")
        ]);
        $this->success();
    }
    public function items()
    {
        $multiple=$this->request->param('multiple','','trim');
        $item_type=$this->request->param('item_type',99,'intval');
        $this->assignconfig("multiple",$multiple);
        $this->assign("multiple", $multiple);
        $this->assign("item_type", $item_type);
        if (!$this->request->isAjax())
        {
            return $this->view->fetch();
        }
        $where2=[];
        if($item_type==1 || $item_type==2){
            $where2['item_type']=$item_type;
        }
        $ItemsModel = new \app\admin\model\deerhome\Items;
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $total = $ItemsModel
                ->with(["gg","cate"])
                ->where($where)
                ->where($where2)
                ->count();
        $list = $ItemsModel
                ->with(["gg","cate"])
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
        $result = array("total" => $total, "rows" => $list);

        return json($result);
    }
    public function cates()
    {
        return $this->view->fetch();
    }
  
    private function data_home(){
        $data=[];
        $data['category']=Db::name("deerhome_cate")->field("id,name,face_image as img")->where("cate_id",0)->where("home",1)->where("status",1)->order("weigh asc")->limit(15)->select();
        foreach ($data['category'] as &$item) {
            $item['img']=cdnurl($item['img']);
            $item['son']=Db::name("deerhome_cate")->where("cate_id",$item['id'])->where("status",1)->column("id");
        }
        return $data;
    }
    /**
     * 设计页面：：商品分类
    */
    public function actions_item_cate(){
        $ruleList = Db::name("deerhome_cate")->field("id as value,name as label,cate_id")->order('weigh ASC,id ASC')->select();
        $list=[];
        $son=[];
        foreach ($ruleList as $k => $v) {
            if($v['cate_id']==0){
                $list[$k]=$v;
                continue;
            }
            $son[$k]=$v;
        }
        foreach ($list as $k => $v) {
            foreach ($son as $k2 => $v2) {
                if($v2['cate_id']==$v['value']){
                    $list[$k]['children'][]=$v2;
                }
            }
        }
        $list=array_values($list);
        $this->success('','',$list);
    }
    public function actions(){
        $type=$this->request->param('type','','trim');
        $key=$this->request->param('key','','trim');
        $cate=$this->request->param('cate/a',[]);
        $data=[];
        $where=[];
        if($type=="item_cate"){
            return $this->actions_item_cate();
        }
        if($type=="zt"){
            $where['status']=1;
            $where['cate']=2;
            $data=Db::name("deerhome_design_pages")->where($where)->field("id,page_title as name")->order("id desc")->paginate(10)->each(function($item, $key){
                $item['img']="";
                $item['action']="/pages/design?id={$item['id']}";
                return $item;
            });
            $this->success('','',$data);
        }
        if($type=="item"){
            if($key){
                $where['name']=['like',"%{$key}%"];
            }
            if(count($cate)==1){
                $ids=Db::name("deerhome_cate")->where("cate_id",$cate[0])->column("id");
                $where['cate_id']=['in',$ids];
            }
            if(count($cate)==2){
                $where['cate_id']=(int)$cate[1];
            }
            $data=Db::name("deerhome_items")->where($where)->field("id,name,face_image as img,price,dw")->where("status",1)->order("id desc")->paginate(10)->each(function($item, $key){
                $item['img']=$item['img']?cdnurl($item['img']):"";
                $item['action']="/pages/productDetail/productDetail?id={$item['id']}";
                return $item;
            });
            $this->success('','',$data);
        }
        if($type=="cate"){
            $ruleList = Db::name("deerhome_cate")->field("id,name,cate_id,face_image as img")->order('weigh ASC,id ASC')->select();
            $list=[];
            $fa=[];
            $son=[];
            foreach ($ruleList as $k => $v) {
                $v['img']=$v['img']?cdnurl($v['img']):"";
                $v['action']="/pages/classify/cate?id={$v['id']}&fid={$v['cate_id']}&n={$v['name']}";
                if($v['cate_id']==0){
                    $v['action']="/pages/classify/cate?fid={$v['id']}&n={$v['name']}";
                }
                if($v['cate_id']==0){
                    $fa[$k]=$v;
                    continue;
                }
                $son[$k]=$v;
            }
            foreach ($fa as $k => $v) {
                \array_push($list,$v);
                foreach ($son as $k2 => $v2) {
                    if($v2['cate_id']==$v['id']){
                        $v2['name']=' ├ '.$v2['name'];
                        \array_push($list,$v2);
                    }
                }
            }
            $data=[];
            $data['total']=count($list);
            $data['data']=$list;
            $data['current_page']=1;
            $this->success('','',$data);
        }
        if($type=="other"){
            $list=[];
            array_push($list,[
                'id'=>'1',
                'name'=>'领取优惠券页面',
                'img'=>'',
                'action'=>'/pages/coupon/coupon'
            ]);
            array_push($list,[
                'id'=>'2',
                'name'=>'微信客服',
                'img'=>'',
                'action'=>'wechat_kefu'
            ]);
            array_push($list,[
                'id'=>'3',
                'name'=>'申请入驻',
                'img'=>'',
                'action'=>'/pages/apply'
            ]);
            $data=[];
            $data['total']=count($list);
            $data['data']=$list;
            $data['current_page']=1;
            $this->success('','',$data);
        }
       
        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
